package com.zbb.online_exam.controller;

import com.zbb.online_exam.constant.Method;
import com.zbb.online_exam.dto.JsonResult;
import com.zbb.online_exam.dto.TableDto;
import com.zbb.online_exam.entity.Question;
import com.zbb.online_exam.exception.ExamException;
import com.zbb.online_exam.service.QuestionService;
import com.zbb.online_exam.utils.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @author zbbstart
 * @date 2021/2/12 - 13:06
 */
@RestController
@RequestMapping("questions")
@Api(tags = "题目管理功能的相关接口")
@Slf4j
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private HttpUtils httpUtils;

    /**
     * 获取所有的题目
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @GetMapping
    @ApiOperation(value = "获取所有的题目", notes = "获取所有的题目")
    public JsonResult getAllQuestions(HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        TableDto tableDto = new TableDto();
        try {
            int pageNo = Integer.parseInt(req.getParameter("page"));
            int pageSize = Integer.parseInt(req.getParameter("limit"));
            log.info("当前题目页码:" + pageNo);
            log.info("页面限制的条数:" + pageSize);
            String q = req.getParameter("q");
            log.info("模糊查询关键字:"+q);
            if ("".equals(q) || null == q){
                tableDto = questionService.getAllQuestionsByPage(pageNo, pageSize);
            }else {
                tableDto = questionService.likeSearchQuestions(q,pageNo, pageSize);
            }
            result = httpUtils.buildSuccess(Method.GET, tableDto);
        } catch (ExamException ee) {
            result = httpUtils.buildFailure(ee.getMessage(), Method.GET);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 新增题目
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @PostMapping
    @ApiOperation(value = "新增题目", notes = "新增题目")
    public JsonResult addQuestion(@ApiParam(name = "token", example = "") @RequestHeader("auth-token") String token,
                                  @RequestBody Question question, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        log.info("新增题目的内容:" + question);
        try {
            questionService.addQuestion(question, token);
            result = httpUtils.buildSuccess(Method.POST, "新增题目成功...");
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 修改题目
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @PutMapping("{teacherNo}")
    @ApiOperation(value = "修改题目", notes = "根据老师的编号修改题目，管理员都能修改")
    public JsonResult updateQuestion(@PathVariable("teacherNo") Integer teacherNo, @RequestBody Question question, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        question.setTeacherNo(teacherNo);
        log.info("修改题目的内容:" + question);
        try {
            questionService.updateQuestion(question);
            result = httpUtils.buildSuccess(Method.PUT, "修改题目成功...");
        } catch (ExamException e) {
            result = httpUtils.buildFailure(e.getMessage(), Method.PUT);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 删除题目
     * 可以是单个题目的删除，也可以是多个题目的删除
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @DeleteMapping
    @ApiOperation(value = "删除题目", notes = "根据前端传来的题目编号删除题目")
    public JsonResult deleteUser(@RequestHeader("auth-token") String token,
                                 @RequestParam("ids") List<Integer> questionIds,
                                 HttpServletResponse res) {
        JsonResult result = new JsonResult();
        log.info("删除题目的编号:" + Arrays.toString(questionIds.toArray()));
        try {
            questionService.deleteQuestions(questionIds, token);
            result = httpUtils.buildSuccess(Method.DELETE);
        }catch (ExamException e) {
            result = httpUtils.buildFailure(e.getMessage(), Method.DELETE);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

}
